<?php
/**
 * Soar Framework - Lightweight and simple to use PHP Framework
 *
 * Soar is free software and is distributed WITHOUT ANY WARRANTY
 *
 * @package Soar
 * @version 1.0 $Id: SoarRequest.php 2 2012-04-06 21:50:33Z shay@shayanderson.com $
 * @copyright Copyright (c) 2012 ShayAnderson.com
 * @license http://www.gnu.org/licenses/gpl.html GPL License
 * @link http://www.shayanderson.com/projects/soar-php-framework.htm
 */

/**
 * Soar Framework Request Handler Class
 *
 * @package Soar
 * @name SoarRequest
 * @author Shay Anderson 03.12
 *
 * @example
 * $get = &SoarRequest::getInstance(SoarRequest::TYPE_GET);
 * $get->id; // ?id=[x]
 */
final class SoarRequest
{
	/**
	 * Request types
	 */
	const TYPE_GET = 0;
	const TYPE_POST = 1;
	const TYPE_SERVER = 2;
	const TYPE_SESSION = 3;

	/**
	 * Request type instances (singleton)
	 *
	 * @var array
	 */
	private static $__instances = array();

	/**
	 * Request vars
	 *
	 * @var array
	 */
	private $__request = array();

	/**
	 * Request type
	 *
	 * @var int
	 */
	private $__type = 0;

	/**
	 * Init request type
	 *
	 * @param int $type
	 */
	private function __construct($type)
	{
		$this->__type = $type;
		if(is_int($this->__type))
		{
			switch($this->__type)
			{
				case self::TYPE_GET:
					$this->__request = &$_GET;
					break;
				case self::TYPE_POST:
					$this->__request = &$_POST;
					break;
				case self::TYPE_SERVER:
					$this->__request = &$_SERVER;
					break;
				case self::TYPE_SESSION:
					$this->__request = &$_SESSION;
					break;
			}
		}
	}

	/**
	 * Do not allow
	 */
	private function __clone(){}

	/**
	 * Request var getter
	 *
	 * @param string $name
	 * @return mixed
	 */
	public function __get($name)
	{
		if($this->__isset($name))
		{
			return $this->__request[$name];
		}
		return NULL;
	}

	/**
	 * Check if request var exists
	 *
	 * @param string $name
	 * @return bool
	 */
	public function __isset($name)
	{
		return isset($this->__request[$name]);
	}

	/**
	 * Request var setter
	 *
	 * @param string $name
	 * @param mixed $value
	 * @return void
	 */
	public function __set($name, $value)
	{
		// only allow setting for certain request types
		if($this->__type != self::TYPE_SERVER)
		{
			$this->__request[$name] = $value;
		}
	}

	/**
	 * Unset request var
	 *
	 * @param string $name
	 * @return void
	 */
	public function __unset($name)
	{
		if($this->__isset($name))
		{
			unset($this->__request[$name]);
		}
	}

	/**
	 * Request type instance getter (singleton)
	 *
	 * @param int $type
	 * @return SoarRequest
	 */
	public static function &getInstance($type)
	{
		if(!isset(self::$__instances[$type]))
		{
			if(count(self::$__instances) < 1)
			{
				Soar::log(__CLASS__ . ': initialized', SoarDebugger::LEVEL_DEBUG);
			}
			self::$__instances[$type] = new self($type);
		}
		return self::$__instances[$type];
	}
}
?>